import { isEmpty } from '@vben/utils';

import dayjs from 'dayjs';
/**
 * 字符串转数组
 * @param queryString
 * @returns
 */
export const queryStringToObject = (
  queryString: string,
): { [key: string]: string } => {
  const params = new URLSearchParams(queryString);
  const result: { [key: string]: string } = {};

  for (const [key, value] of params.entries()) {
    result[key] = value;
  }

  return result;
};

type InputObject = Record<string, any>;

type OutputObject = Record<string, any>;

/**
 * 合并两个对象并格式化输出
 * @param object1 - 包含字段信息的源对象数组
 * @param object2 - 包含值的对象
 * @param fields - 输出对象需要的字段名数组
 * @returns 格式化后的对象数组
 */
/**
 * 合并两个对象并格式化输出
 * @param object1 - 包含字段信息的源对象数组
 * @param object2 - 包含值的对象
 * @param fields - 输出对象需要的字段名数组
 * @param nameKey - 决定从 object2 中取值的键名
 * @returns 格式化后的对象数组
 */
export function mergeObjects(
  object1: any,
  object2: InputObject,
  fields: string[],
  nameKey: string,
): OutputObject[] {
  return object1.map((item: any) => {
    const valueFromObject2 =
      object2[item[nameKey] as string] === 0
        ? '0'
        : object2[item[nameKey] as string] || '';
    const mergedItem: OutputObject = {};

    fields.forEach((field) => {
      mergedItem[field] = field === 'value' ? valueFromObject2 : item[field];
    });

    return mergedItem;
  });
}

type ConfigItem = {
  data?: any;
  dataSource?: Record<string, any>;
  default_value?: any;
  item?: Record<string, any>;
  name?: string;
  options?: Record<string, string>;
  tip?: string;
  title?: string;
  type: string;
  value?: any;
};
/** 根据配置动态生成表单结构 */
export function generateFormSchema(config: Record<string, ConfigItem>) {
  const schema: any[] = [];
  const values: Record<any, any> = {};

  const typeToComponentMap: Record<
    ConfigItem['type'],
    {
      component: string;
      componentProps?: Record<string, any>;
      defaultValue: any;
    }
  > = {
   
    array: {
      component: 'FileBlockWidgetInput',
      defaultValue: [],
      componentProps: {},
    },
    checkbox: {
      component: 'CheckboxGroup',
      defaultValue: [],
      componentProps: {},
    },
    color: {
      component: 'ColorPicker',
      defaultValue: '#000',
      componentProps: { placeholder: '请选择' },
    },
    date: {
      component: 'DatePicker',
      defaultValue: '',
      componentProps: {
        format: 'YYYY-MM-DD',
        mode: 'date',
      },
    },
    datetime: { component: 'TimePicker', defaultValue: '' },
    file: {
      component: 'Upload',
      defaultValue: '',
      componentProps: { type: 'file' },
    },
    files: {
      component: 'Upload',
      defaultValue: [],
      componentProps: { type: 'file', multiple: true },
    },
    image: { component: 'Upload', defaultValue: '' },
    images: {
      component: 'Upload',
      defaultValue: [],
      componentProps: { multiple: true },
    },
    location: {
      component: 'Location',
      defaultValue: '',
      componentProps: { placeholder: '请选择' },
    },
    number: {
      component: 'InputNumber',
      defaultValue: 0,
      componentProps: { placeholder: '请输入' },
    },
    password: {
      component: 'InputPassword',
      defaultValue: '',
      componentProps: { placeholder: '请输入' },
    },
    radio: { component: 'RadioGroup', defaultValue: '' },
    select: {
      component: 'Select',
      defaultValue: '',
      componentProps: {
        placeholder: '请选择',
        class: 'w-full',
        allowClear: true,
      },
    },
    text: {
      component: 'Input',
      defaultValue: '',
      componentProps: { placeholder: '请输入' },
    },
    textarea: {
      component: 'Textarea',
      defaultValue: '',
      componentProps: { placeholder: '请输入' },
    },
    cascader: {
      component: 'DataSourceSelect',
      defaultValue: '',
      componentProps: { placeholder: '请输入' },
    },
    article_dataSource: {
      component: 'DataSourceSelect',
      defaultValue: '',
      componentProps: { placeholder: '请输入' },
    },
    rich_text: {
      component: 'RichText',
      defaultValue: '',
      componentProps: { placeholder: '请输入' },
    },
    html: {
      component: 'Editor',
      defaultValue: '',
      componentProps: { placeholder: '请输入' },
    },
  };

  for (const [key, configItem] of Object.entries(config)) {
    const fieldName = configItem?.name ?? key;
    const typeMapping = typeToComponentMap[configItem.type];
    if (!typeMapping) {
      console.warn(`Unsupported config type: ${configItem.type}`);
      continue;
    }
    configItem.value = configItem.value ?? configItem?.default_value;
    const { component, defaultValue, componentProps = {} } = typeMapping;
    // 判断configItem.options是否为数组,如果是数组则将其赋值给options,如果是对象则遍历对象成为一个新数组如[value:"李四",label:"姓名"]，否则赋值为undefined
    let options: any = [];
    if (Array.isArray(configItem.options)) {
      // 遍历数组，如果value是数字则转化为数字
      options = configItem.options.map((option: any) => ({
        value: /^\d+$/.test(option) ? Number(option) : option,
        label: option,
      }));
    } else if (
      typeof configItem.options === 'object' &&
      !Array.isArray(configItem.options)
    ) {
      options = Object.entries(configItem.options).map(([value, label]) => ({
        value: /^\d+$/.test(value) ? Number(value) : value,
        label,
      }));
    } else {
      options = undefined;
    }
    let dataSource = configItem?.dataSource ?? undefined;
    const item = configItem?.item ?? undefined;

    // 级联数据源
    if (configItem.type === 'cascader') {
      dataSource = {
        api: 'portal/linkage/index',
        multi: false,
        data: configItem.data,
      };
      options = configItem.options;
    }

    // 文章数据源
    if (configItem.type === 'article_dataSource') {
      dataSource = {
        api: 'portal/article/index',
        multi: true,
      };
      options = configItem.options;
    }

    if (
      options &&
      options[0] &&
      /^\d+$/.test(options[0].value) &&
      options[0].value === 0
    ) {
      options = options.map((option: any) => ({
        label: option.label,
        value: Number(option.value),
      }));
      configItem.value = configItem.value ? Number(configItem.value) : '';
    }

    schema.push({
      fieldName,
      label: configItem.title || '',
      help: configItem.tip || '',
      component: dataSource ? 'DataSourceSelect' : component,
      componentProps: {
        ...componentProps,
        ...(options ? { options } : {}),
        ...(dataSource ? { dataSource } : {}),
        ...(item ? { item } : {}),
        ...(configItem.title ? { title: configItem.title } : {}),
      },
    });
    values[fieldName] = isEmpty(configItem.value)
      ? defaultValue
      : configItem.value;

    if (values[fieldName] && /^\d+$/.test(values[fieldName])) {
      values[fieldName] = Number(values[fieldName]);
    }
    // 判断type是否为checkbox
    if (configItem.type === 'checkbox' && options) {
      values[fieldName] = values[fieldName] || [];
      // 判断values[fieldName]是否有值并且是字符串，如果是字符串则将其分割为数组
      values[fieldName] =
        !isEmpty(values[fieldName]) && typeof values[fieldName] === 'string'
          ? (values[fieldName] as string).split(',')
          : values[fieldName];
      // 判断values[fieldName]是否有值并且是数组，如果是如果不是数组则转化为数组,
      values[fieldName] =
        !isEmpty(values[fieldName]) && !Array.isArray(values[fieldName])
          ? [values[fieldName]]
          : values[fieldName];
      // 判断options第一位是否为数字，如果是数字则将values[fieldName]转化为数字数组
      values[fieldName] = /^\d+$/.test(options[0].value)
        ? values[fieldName].map(Number)
        : values[fieldName];
    }

    if (configItem.type === 'date') {
      values[fieldName] = isEmpty(configItem.value)
        ? dayjs(new Date())
        : dayjs(configItem.value);
    }

    if (configItem.type === 'datetime') {
      values[fieldName] = isEmpty(configItem.value)
        ? dayjs(new Date())
        : dayjs(configItem.value);
    }
  }
  return { schema, values };
}

/**
 * 格式化动态表单提交的值，component等于DatePicker转化为日期TimePicker为时间
 * @param formApiStateSchema
 * @param values
 * @returns
 */
export function formatValues(
  formApiStateSchema: any[],
  values: { [key: string]: string },
): { [key: string]: string } {
  const formattedValues: { [key: string]: string } = {};

  formApiStateSchema.forEach((item) => {
    const { fieldName, component } = item;
    const value = values[fieldName];

    // 如果值存在
    if (value !== undefined) {
      if (component === 'DatePicker') {
        // 格式化为日期（按 YYYY-MM-DD 格式）
        formattedValues[fieldName] = dayjs(value).format('YYYY-MM-DD');
      } else if (component === 'TimePicker') {
        // 格式化为时间（按 HH:mm:ss 格式）
        formattedValues[fieldName] = dayjs(value, 'HH:mm:ss').format(
          'YYYY-MM-DD HH:mm:ss',
        );
      } else {
        // 如果是其他组件，保持原值
        formattedValues[fieldName] = value;
      }
    }
  });

  return formattedValues;
}

/**
 * 生成随机唯一码
 * @param length 需要生成的长度默认8个字符
 * @returns uniqueCode
 */
export function generateUniqueCode(length: number = 8): string {
  let code = '';
  const characters =
    'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

  for (let i = 0; i < length; i++) {
    const randomIndex = Math.floor(Math.random() * characters.length);
    code += characters[randomIndex];
  }

  return code;
}
